<template>
  <div>
    <px-row style="min-height: 64px">
      <px-col :span="24" class="water_col">
        <div class="waterdom borderRidus" style="height: 100%">
          <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
            <px-form-item label="统计维度">
              <px-select v-model="queryParams.dimension" placeholder="请选择" clearable style="width: 210px" filterable @change="timechange">
                <px-option v-for="dict in dimensionList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item v-if="queryParams.dimension == 'Y'" label="年份">
              <!-- <px-date-picker v-model="queryParams.Time" type="year" placeholder="请选择" /> -->
              <yearPicker :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </px-form-item>
            <px-form-item v-if="queryParams.dimension == 'M'" label="月份">
              <px-date-picker
                v-model="queryParams.Time"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                placeholder="请选择"
                format="YYYY-MM"
                value-format="YYYY-MM"
                @change="settime"
              />
            </px-form-item>
            <px-form-item label="厂区">
              <px-select v-model="queryParams.level" :disabled="facDisabled" placeholder="请选择厂区" clearable style="width: 210px" filterable>
                <px-option v-for="dict in levList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item label="核算边界">
              <px-select v-model="queryParams.templateId" placeholder="请选择" style="width: 210px" filterable @change="getrelationIds">
                <px-option v-for="dict in typeList" :key="dict.id" :label="dict.templateName" :value="dict.id" />
              </px-select>
            </px-form-item>
            <px-form-item label="设施/活动">
              <px-tree-select
                v-model="queryParams.relationIds"
                default-expand-all
                placeholder="请选择"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max="3"
                :props="defaultProps"
                style="width: 100%"
                :data="FacilityList"
                :render-after-expand="false"
              />
            </px-form-item>
            <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery()">查询</px-button>
            <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
          </px-form>
        </div>
      </px-col>
    </px-row>
    <px-row v-if="trendDataDTOList.length > 0" style="height: 732px; margin-top: 16px" :gutter="16">
      <px-col :span="8" class="water_col">
        <div class="waterdom borderRidus" style="position: relative; height: 716px">
          <modelTitle :title="'设施活动碳排放量排行'" />
          <px-button type="primary" style="position: absolute; top: 16px; right: 32px" plain @click="handleExportall">导出</px-button>
          <div class="model_chart">
            <px-table :data="emissionRankingDataDTOList[0]?.emissionRankingDTOList" :border="false" stripe style="width: 100%" height="644px">
              <px-table-column type="index" width="50" label="排行" />
              <px-table-column prop="level" label="厂区" />
              <px-table-column prop="facilityName" label="设施活动名称" />
              <px-table-column prop="carbonEmission" label="碳排放量(tCO₂e)" />
            </px-table>
          </div>
        </div>
      </px-col>
      <px-col :span="16">
        <px-row :gutter="16">
          <px-col v-for="(item, index) in trendDataDTOList" :key="index" :span="12" class="water_col">
            <div style="height: 350px; margin-bottom: 16px" class="waterdom borderRidus">
              <modelTitle :title="trendDataDTOList[index].facilityName" />
              <div class="model_chart" style="margin-top: 16px">
                <chartswwt :chartvlue="trendDataDTOList[index]" style="width: 100%" :width="'100%'" :height="'270px'" />
              </div>
            </div>
          </px-col>
        </px-row>
      </px-col>
    </px-row>
    <template v-else>
      <px-empty :image-size="200" />
    </template>
  </div>
</template>
<script setup lang="ts">
import { accountingTemplatequery } from "@/api/doubleCarbonManage/accountingBoundary";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import chartsParent from "./components/chartsParent.vue";
import chartswwt from "./components/chartswwt.vue";
import chartswwt2 from "./components/chartswwt2.vue";
import chartswwt3 from "./components/chartswwt3.vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import chartsUpwChemistry from "./components/chartsUpwChemistry.vue";
import chartsIndexUpw from "./components/chartsIndexUpw.vue";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { accountingEmissionDatagetFacilityList, accountingEmissionDataemissionTrend } from "@/api/doubleCarbonManage/comparisonStandard";
const data = reactive({
  FacilityList: [],
  dimensionList: [
    {
      itemName: "月度",
      itemValue: "M"
    },
    {
      itemName: "年度",
      itemValue: "Y"
    }
  ],
  levList: [
    {
      itemName: "全厂",
      itemValue: null
    },
    {
      itemName: "创新中心一期",
      itemValue: "创新中心一期"
    },
    {
      itemName: "创新中心二期",
      itemValue: "创新中心二期"
    }
  ],
  queryParams: {
    dimension: "M",
    startDate: "",
    endDate: "",
    level: null,
    Time: [],
    relationIds: [],
    templateId: ""
  },
  montime: [],
  yeartime: "",
  tableData: [
    {
      taskNo: "1",
      taskName: "创新中心1期",
      responsible: "外购热",
      status: "159916.67"
    }
  ],
  trendDataDTOList: [],
  emissionRankingDataDTOList: [],
  typeList: []
});
const liquidList = [
  {
    itemValue: "外购热"
  },
  {
    itemValue: "外购电"
  },
  {
    itemValue: "废气燃烧装置"
  }
];
const defaultProps = {
  children: "facilities",
  label: "name",
  value: "id"
};
const { typeList, trendDataDTOList, emissionRankingDataDTOList, FacilityList, queryParams, tableData, dimensionList, montime, yeartime, levList } =
  toRefs(data);
const dateValue = ref<any>({ startYear: new Date().getFullYear() - 4, endYear: new Date().getFullYear() });
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  queryParams.value.Time = [startYear.toString(), endYear.toString()];
  queryParams.value.startDate = `${startYear}-01-01 00:00:00`;
  queryParams.value.endDate = `${endYear}-12-31 23:59:59`;
};
const { proxy }: any = getCurrentInstance();
const handleExportall = () => {
  allData.value.type = "table";
  allData.value.name = "设施活动碳排放量排行";
  proxy.download("post", "/energy/accountingEmissionData/exportEmissionTrend", allData.value);
};
const allData = ref({});
const handleQuery = () => {
  let parmas = {
    dimension: queryParams.value.dimension,
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    level: queryParams.value.level,
    relationIds: queryParams.value.relationIds,
    templateId: queryParams.value.templateId
  };
  accountingEmissionDataemissionTrend(parmas).then(res => {
    allData.value = res;
    trendDataDTOList.value = res.trendDataDTOList;
    emissionRankingDataDTOList.value = res.emissionRankingDataDTOList;
  });
};
const resetQuery = () => {
  queryParams.value.startDate = `${new Date().getFullYear()}-01-01 00:00:00`;
  queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
  queryParams.value.Time = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
  queryParams.value.dimension = "M";
  queryParams.value.level = null;
  queryParams.value.templateId = typeList.value[0]?.id;
  if (localStorage.getItem("facList")) {
    let faclist = JSON.parse(localStorage.getItem("facList"));
    if (faclist.length == 1) {
      facDisabled.value = true;
      queryParams.value.level = faclist[0].name;
      getList();
    } else if (faclist.length == 2) {
      facDisabled.value = false;
      queryParams.value.level = null;
      getList();
    }
  }
};
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
const timechange = val => {
  if (val == "Y") {
    queryParams.value.startDate = `${dateValue.value.startYear}-01-01 00:00:00`;
    queryParams.value.endDate = `${dateValue.value.endYear}-12-31 23:59:59`;
  } else {
    queryParams.value.startDate = `${queryParams.value.Time[0]}-01 00:00:00`;
    queryParams.value.endDate = `${queryParams.value.Time[1]}-31 23:59:59`;
  }
};
let facDisabled = ref(false);
onMounted(() => {
  accountingTemplatequery({
    orderByColumn: "",
    isAsc: "",
    templateName: "",
    templateStatus: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 999
  }).then((response: any) => {
    typeList.value = response.data;
    queryParams.value.templateId = response.data[0]?.id;
    // getList();
    if (localStorage.getItem("facList")) {
      let faclist = JSON.parse(localStorage.getItem("facList"));
      if (faclist.length == 1) {
        facDisabled.value = true;
        queryParams.value.level = faclist[0].name;
        getList();
      } else if (faclist.length == 2) {
        facDisabled.value = false;
        queryParams.value.level = null;
        getList();
      }
    }
  });
});
const getrelationIds = () => {
  queryParams.value.relationIds = [];
  getList();
};
const getList = () => {
  if (new Date().getMonth() == 0) {
    queryParams.value.startDate = `${new Date().getFullYear() - 1}-01-01 00:00:00`;
    queryParams.value.endDate = `${new Date().getFullYear() - 1}-12-31 23:59:59`;
    queryParams.value.Time = [`${new Date().getFullYear() - 1}-01`, `${new Date().getFullYear() - 1}-12`];
    accountingEmissionDatagetFacilityList({
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      FacilityList.value = res;
      if (res != null) {
        FacilityList.value = res;
        setDefaultValues();
        setTimeout(() => {
          handleQuery();
        }, 500);
      } else {
        FacilityList.value = [];
        queryParams.value.relationIds = [];
        trendDataDTOList.value = [];
      }
    });
  } else {
    queryParams.value.startDate = `${new Date().getFullYear()}-01-01 00:00:00`;
    queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
    queryParams.value.Time = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
    accountingEmissionDatagetFacilityList({
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate,
      templateId: queryParams.value.templateId
    }).then(res => {
      console.log(res);
      if (res != null) {
        FacilityList.value = res;
        setDefaultValues();
        setTimeout(() => {
          handleQuery();
        }, 500);
      } else {
        FacilityList.value = [];
        queryParams.value.relationIds = [];
        trendDataDTOList.value = [];
      }
    });
  }
};

const setDefaultValues = () => {
  queryParams.value.relationIds = [];
  console.log(FacilityList.value);
  FacilityList.value.forEach(item => {
    if (item.facilities && item.facilities.length > 0) {
      item.facilities.forEach(item => {
        if (item.mark == "Y") {
          queryParams.value.relationIds.push(item.id);
        }
      });
    }
  });
};
const settime = val => {
  console.log(val);
  queryParams.value.startDate = `${val[0]}-01 00:00:00`;
  queryParams.value.endDate = `${val[1]}-31 23:59:59`;
};
</script>

<style scoped lang="scss">
.water_col {
  height: 100%;
}

.waterdom {
  width: 100%;
  height: 360px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.first_width {
  width: calc(100% - 16px);
}

.model_chart {
  position: relative;
  width: 100%;
  height: calc(100% - 40px);
  margin-top: 10px;

  .co2img {
    position: absolute;
    top: 32px;
    left: 22px;
    width: 32px;
    height: 32px;
  }

  .titlep {
    position: absolute;
    top: 29px;
    left: 70px;
    font-size: 16px;
    font-weight: 400;
    color: #000;
  }

  .titlevalue {
    position: absolute;
    top: 55px;
    left: 70px;

    .titlevalue1 {
      float: left;
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      color: #3b82f6;
    }

    .titlevalue1span {
      font-size: 16px;
      font-weight: 400;
      line-height: 22px;
      color: #4f4f4f;
    }

    .titlevalue2 {
      float: left;
      margin-top: 5px;
      margin-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #f87171;
    }
  }

  .co2mian {
    position: absolute;
    top: 112px;
    left: 0;
    width: 100%;
    height: 92px;
  }

  .co2mianleft {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianleftp {
      width: calc(100% - 21px);
      height: 22px;
      padding-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
      border-right: 1px solid #cbcdd8;
    }
  }

  .co2mianright {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianrightp {
      width: calc(100% - 45px);
      height: 22px;
      padding-left: 45px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }
  }

  .co2mianleftp2 {
    margin-left: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;

    .co2mianleftp2span {
      font-size: 14px;
      font-weight: 400;
      color: #4f4f4f;
    }
  }

  .co2mianleftp3 {
    float: left;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #000;

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #34d399;
    }
  }
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 26px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 16px;
}

.percentage-value2 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}

.percentage-label2 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.percentage-value3 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  color: #f00;
}

.percentage-label3 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #f00;
}

.jindu1 {
  margin: 24px 0 0 17px;
}

.jindu2 {
  margin: 38px calc((100% - 103px) / 2);
}

.jindu1p {
  width: calc(100% - 24px);
  margin-top: 0;
  font-size: 16px;
  text-align: center;
}

.jindu2p {
  width: 100%;
  margin-top: -40px;
  font-size: 14px;
  text-align: center;
}

:deep(.px-table) {
  .px-table__cell {
    padding: 6px 0;
  }

  td,
  tr {
    border: none;
  }

  .px-table__header-wrapper,
  .px-table__fixed-header-wrapper {
    th {
      background-color: white !important;
      border: none;
    }
  }
}

:deep(.px-table--striped .px-table__body tr.px-table__row--striped td.px-table__cell) {
  background-color: rgb(231 238 251 / 50%) !important;
}

:deep(.px-table__inner-wrapper::before) {
  background: none;
}
</style>
